<?php
/**
 * Author: Silent Night
 * email: silentwolf_wp@163.com
 * Date: 2017/10/10
 * Time: 11:02
 */

namespace app\admin\model;

use think\Model;
use think;

class Dep extends Model
{


    public function getID($pid)
    {
        $data = array();
        $res = $this->where(['id' => $pid])
            ->find();
        if ($res) {
            $data = $res->toArray();
        }
        return $data;
    }

    public function lists($w, $pagesize = "10")
    {

        $rdata = array();
        if (!empty($w))
            $this->where($w);
        $this->order("id", "asc");
        $list = $this->paginate($pagesize)->toArray();
//         echo $this->getLastSql();
        return $list;
    }

    public function getDataForWhere($w)
    {
        $data = array();
        $res = $this->where($w)
            ->find();
        if ($res) {
            $data = $res->toArray();
        }
        return $data;
    }

    public function getDataForWheres($w)
    {
        $data = array();
        $res = $this->where($w)
            ->select();
        if ($res) {
            $data = $res->toArray();
        }
        return $data;
    }

    public function getAll($w = array())
    {
        $data = array();
        if (!empty($w)) {
            $this->where($w);
        }
        $res = $this->select();
        if ($res) {
            $data = $res->toArray();
        }
        return $data;
    }

    public function getAllDep()
    {
        $all = array();
        $first = $this->getDataForWheres(array('level' => 0));


        $second = $this->getDataForWheres(array('level' => 1));

        foreach ($first as $key => $val) {
            $first[$key]['second'] = array();
            foreach ($second as $k => $v) {
                if (!empty($v)) {
                    $first[$key]['second'][] = $v;
                }

            }
        }
        $first_mk = array();
        foreach ($first as $k => $v) {
            $first_mk[$v['id']] = $v;
        }
        $second_mk = array();
        foreach ($second as $k => $v) {
            $second_mk[$v['id']] = $v;
        }

        $all = array_merge($first_mk, $second_mk);

        $rData = array(
            'all' => $all,
            'first' => $first,
            'second' => $second,
            'first_mk' => $first_mk,
            'second_mk' => $second_mk
        );

        return $rData;

    }


    public function updateData($update, $id)
    {
        $res = $this->save($update, ['id' => $id]);
        return $res;
    }

    public function updateDataForArr($update, $where)
    {
        $res = $this->save($update, $where);
        return $res;
    }

    public function updateDataForWhere($update, $where)
    {
        $res = $this->save($update, $where);
        return $res;
    }

    public function add($array)
    {
        $this->save($array);
        return $this->getLastInsID();
    }

    public function delData($w)
    {

        return $this->where($w)->delete();
    }


}